package jxjc

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type LinuxList struct {
	ID       int    `gorm:"column:id;primaryKey;autoIncrement"`
	Username string `gorm:"column:username"`
	Host     string `gorm:"column:host"`
	Stime    string `gorm:"column:stime"`
	Filename string `gorm:"column:filename"`
}

func Linux_select() []string {
	dsn := "root:123456@tcp(127.0.0.1:3306)/nsisp?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	// 如果没有表则创建表
	db.AutoMigrate(&LinuxList{})

	var s []LinuxList
	if err := db.Model(&LinuxList{}).Find(&s).Error; err != nil {
		panic(err)
	}

	var result []string
	for _, item := range s {
		formatted := fmt.Sprintf("%d，%s，%s，%s，%s", item.ID, item.Username, item.Host, item.Stime, item.Filename)
		result = append(result, formatted)
	}

	return result
}

func Linux_insert(username string, host string, stime string, filename string) error {
	dsn := "root:123456@tcp(127.0.0.1:3306)/nsisp?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	//如果没有表则创建表
	db.AutoMigrate(&LinuxList{})
	var linux = LinuxList{
		Username: username,
		Host:     host,
		Stime:    stime,
		Filename: filename,
	}
	//向表中插入数据
	if err := db.Model(&LinuxList{}).Create(&linux).Error; err != nil {
		panic(err)
	}
	return nil
}

func Linux_delete(id int) {
	dsn := "root:123456@tcp(127.0.0.1:3306)/nsisp?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	//如果没有表则创建表
	db.AutoMigrate(&LinuxList{})
	//删除表中的数据
	if err := db.Model(&LinuxList{}).Where("id = ?", id).Delete(&LinuxList{}).Error; err != nil {
		panic(err)
	}
}

func main() {

}
